package com.dodock.android.banglapapers.ui;

import java.util.Vector;

import org.json.JSONArray;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dodock.android.banglapapers.BanglaNews;
import com.dodock.android.banglapapers.ComplexScriptHelper;
import com.dodock.android.banglapapers.InternetConnectivity;
import com.dodock.android.banglapapers.MyApplication;
import com.dodock.android.banglapapers.NewsDetails;
import com.dodock.android.banglapapers.NewsList;
import com.dodock.android.banglapapers.R;
import com.dodock.android.banglapapers.WebServerOperation;
import com.dodock.android.banglapapers.imageLoader.ImageLoader;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

public class TopNewsActivity extends BaseActivity{

	private ProgressDialog progressDialog;
	private boolean bError = false;
	private String id = "";
	private Typeface fontBN;
	private Typeface fontEN;
	public static Vector<NewsList> newsList;
	int newsPaperNo = 0;
	private int list[];
	private int newsNo = 0;
	
	private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		//Google Analytics
		try{
		    mGaInstance = GoogleAnalytics.getInstance(this);
		    mGaTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
		}
		catch (Exception e) {
		}
		//--Google Analytics
				
		
		
		setContentView(R.layout.news_category);	
		TextView titleView = (TextView) findViewById(R.id.title);
		titleView.setText(R.string.topNews);
		
		ImageButton settingsButton = (ImageButton) findViewById(R.id.settingsBtn);
		settingsButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				settingsActivity();
			}
		});

		newsList = new Vector<NewsList>();
		fontBN = Typeface.createFromAsset(this.getAssets(), "font/SutonnyMJ.ttf");
		fontEN = Typeface.DEFAULT;
		Button topNewsButton = (Button) findViewById(R.id.topNews);
		topNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				Intent intent = new Intent(TopNewsActivity.this, TopNewsActivity.class);
//				startActivity(intent);
			}
		});

		Button favouritButton = (Button) findViewById(R.id.favorite);
		favouritButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(TopNewsActivity.this, FavouritNewsActivity.class);
				startActivity(intent);
			}
		});

		Button savedNewsButton = (Button) findViewById(R.id.savedNews);
		savedNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(TopNewsActivity.this, SavedNewsActivity.class);
				startActivity(intent);
			}
		});
		
		ImageView refreshButton = (ImageView) findViewById(R.id.refresh);
		refreshButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadNewsList();
			}
		});
		
		loadNewsList();
	}
	
	private void loadNewsList() {
		if(HomeActivity.newspapersList != null && HomeActivity.newspapersList.size() > 0)
		{
			list = new int[HomeActivity.newspapersList.size() + 1];
			if (InternetConnectivity.isConnectedToInternet(this)) {
				progressDialog = ProgressDialog.show(this, null, "Loading. Please wait...", true, false);
				GetTopNewsList getNewsList = new GetTopNewsList();
				getNewsList.execute();
			} else {
				Toast toast = Toast.makeText(this,"Enable mobile network or Wi-Fi to download data",Toast.LENGTH_LONG);
				toast.show();
			}
		}
	}
	
	private class GetTopNewsList extends AsyncTask<Void, Void, Void> {
		
		@Override
		protected Void doInBackground(Void... params) {
			getTopNewsListJson();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			try{
				progressDialog.dismiss();
				progressDialog = null;
				if (!bError){
					showContentView();
				}
			}
			catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	private void showContentView() {
		// TODO Auto-generated method stub
		LinearLayout mainContainer = (LinearLayout) findViewById(R.id.newsCategoryMainContainer);
		
		for (int newsNo = 0; newsNo < newsList.size(); newsNo++) {
			if(list[newsPaperNo] == newsNo && newsPaperNo <= HomeActivity.newspapersList.size() ){
				LinearLayout container = new LinearLayout(this);
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.MATCH_PARENT, 80);
				container.setLayoutParams(params);
				params.setMargins(0, 25, 0, 0);
				container.setBackgroundResource(R.drawable.roundtopgray_normal);
				container.setGravity(Gravity.CENTER);
				ImageLoader imageLoader = new ImageLoader(this);
				ImageView logo = new ImageView(this);
				LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT, BanglaNews.SCREEN_WIDTH/2);
				logo.setLayoutParams(logoParams);
				imageLoader.DisplayImage(BanglaNews.BASE_URL + HomeActivity.newspapersList.get(newsPaperNo).getLogo(),
						R.drawable.logo, logo, true, container);
				mainContainer.addView(container);
				newsPaperNo++;
			}
			
			LinearLayout newsCategoryLayout = (LinearLayout) LayoutInflater.from(
					getBaseContext()).inflate(R.layout.news_list_single_item, null);
			TextView titleTextview = (TextView) newsCategoryLayout.findViewById(R.id.newsListTitle);
			if(HomeActivity.newspapersList.get(newsPaperNo - 1).getLanguage().equals("bn")){
				titleTextview.setTypeface(fontBN);
				titleTextview.setText(ComplexScriptHelper.UnicodeToAnsi(newsList.elementAt(newsNo).getTitle()));
			}else{
				titleTextview.setTypeface(fontEN);
				titleTextview.setText(newsList.elementAt(newsNo).getTitle());
			}
			LinearLayout container = (LinearLayout) newsCategoryLayout.findViewById(R.id.newsListImageContainer);
			ImageView image = (ImageView) newsCategoryLayout.findViewById(R.id.newsListImage);
			if(!newsList.get(newsNo).getImage().equals("noimage")){
				ImageLoader imageLoader = new ImageLoader(this);
				imageLoader.DisplayImage(newsList.get(newsNo).getImage(),R.drawable.logo, image, true, container);
			}else
				image.setImageResource(R.drawable.logo);
			
			final int position = newsNo;
			final int paperNo = newsPaperNo - 1;
			newsCategoryLayout.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(TopNewsActivity.this, NewsDetailsActivity.class);
					intent.putExtra("newsPaperId", HomeActivity.newspapersList.get(paperNo).getId());
					intent.putExtra("newsId", newsList.elementAt(position).getId());
					intent.putExtra("newsNo", position);
					intent.putExtra("language", HomeActivity.newspapersList.get(paperNo).getLanguage());
					intent.putExtra("parent", "TopNews");
					startActivity(intent);
				}
			});
			mainContainer.addView(newsCategoryLayout);
		}
	}

	private void getTopNewsListJson() {
		// TODO Auto-generated method stub
		list[0] = 0;
		for (int i = 0; i < HomeActivity.newspapersList.size(); i++) {
			id = HomeActivity.newspapersList.get(i).getId();
			String urlPath = BanglaNews.BASE_URL + "DDNGetNewsList" + "?id="
					+ id + "&catid=" + "top" + "&appVersion="+MyApplication.app_version;
			try {
				String serverResonse = WebServerOperation.HTTPrequest(urlPath);
				parseNewsListJSON(serverResonse);
			} catch (Exception e) {
				Log.e("TopNewsActivity", "getTopNewsListJson() : "+e.toString());
				bError = true;
			}
			list[i+1] = newsNo;
		}
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		try {
			mGaTracker.sendView("/TopNews");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
	}
	
	

	
	private void parseNewsListJSON(String serverResonse) throws Exception{
		// TODO Auto-generated method stub
		JSONArray jsonArray = new JSONArray(serverResonse);
		for (int j = 0; j < jsonArray.length(); j++) {
			NewsList category = new NewsList();
			category.setId(jsonArray.getJSONObject(j).getString("id"));
			category.setTitle(jsonArray.getJSONObject(j).getString("title"));
			if(jsonArray.getJSONObject(j).has("image"))
				category.setImage(jsonArray.getJSONObject(j).getString("image"));
			else
				category.setImage("noimage");
			if(jsonArray.getJSONObject(j).has("details")){
				NewsDetails newsDetails = new NewsDetails();
				newsDetails.setId(jsonArray.getJSONObject(j).getString("id"));
				newsDetails.setSharelink(jsonArray.getJSONObject(j).getString("sharelink"));
				newsDetails.setDetailsNews(jsonArray.getJSONObject(j).getString("details"));
				newsDetails.setTitle(jsonArray.getJSONObject(j).getString("title"));
				if(jsonArray.getJSONObject(j).has("gallery")){
					Vector<String> galleryUrlList = new Vector<String>();
					JSONArray galleryArray = jsonArray.getJSONObject(j).getJSONArray("gallery");
					for(int i = 0; i < galleryArray.length(); i++){
						galleryUrlList.add(galleryArray.getJSONObject(i).getString("url"));
					}
					newsDetails.setGalleryUrlList(galleryUrlList);
					newsDetails.setGalleryFlag(true);
				}else{
					newsDetails.setGalleryUrlList(null);
				}
				category.setNewsDetailsFlag(true);	
				category.setNewsDetails(newsDetails);
			}				
			else{
				category.setNewsDetailsFlag(false);
			}
			newsList.add(category);
			newsNo ++;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		com.facebook.Settings.publishInstallAsync(this, MyApplication.fb_app_id);
	}
	
}
